#!/usr/bin/env python
"""
 Apache.py

 The apache class is the link between the Athabaskan gui and the httpd.conf
 files. The class provides a specific api to make it easy to do common web
 configurations...
 - Jay Smit
"""

from ConfigIO import ConfigIO
from ConfigNode import *
from NodeHandler import MapDirective
import pdb

def print_nodes( node ):
    for n in node.children:
        print n.children
        print_nodes(n)
    
class Apache:
    """
    This is a higher level class that handles server settings for version 2.0
    config files...
    """
    def __init__(self, path):
        """
        Initialise the ConfigNode that we'll be wrapping...
        """
        self.config_tree = ConfigNode()
        self.config_tree.setConfigIO( ConfigIO() )
        self.root = self.config_tree.read_config(path)
        ################## HACK ####################
        ## Just until this reads external files ####
        ############################################
        self.set_document_root("\"/var/www\"")
    
    def set_server_config(self, directive, args):
        """Generic function to add/set server directives"""
        node = self.root.get_node(directive)
        if node is None:
            node = MapDirective(directive, args)
            self.root.add_node(node)
        else:
            node.args = args
    
    def set_server_root(self, server):
        self.set_server_config("ServerRoot", server)
    
    def set_document_root(self, docroot):
        self.set_server_config("DocumentRoot", docroot)
    
    def set_accept_filter(self, filt):
        self.set_server_config("AcceptFilter", filt)
    
    def set_accept_mutex(self, mutex):
        self.set_server_config("AcceptMutex", mutex)
    
    def get_directory(self, args):
        node = self.root.search_tree(
                 lambda n: n.directive == "Directory" and n.args == args)
        return node

#---------------------------------------------------------------------------
    def get_directive(self, directive):
        node = self.root.search_tree(
                 lambda n: n.directive.lower() == directive.lower())
        return node
#---------------------------------------------------------------------------

    def add_to_directory(self, directory, directive, args):
        node = directory.get_node(directive)
        if node is None:
            node = MapDirective(directive, args)
            directory.add_node(node)
        else:
            node.args = args
    
    def save_config(self, path):
            self.config_tree.write_config(path, self.root)

if __name__ == "__main__":
    ap = Apache("httpd.conf")
#    print Apache("httpd.conf").get_directive("DocumentRoot").args
    directory = ap.get_directory(["/var/www/root"])
    if not directory is None:
        ap.add_to_directory(directory, "User", ["Jay"])
    ap.set_server_root(["/my/server/root"])
    ap.set_document_root(["/HOMEBREWED/DOC/ROOT"])
    ap.save_config("file.out")
